package com.mm.learn.shopping.cart;/**
 * @author wdx
 * @create 2021-07-27 13:21
 */

import cn.hutool.json.JSONUtil;
import com.mm.learn.shopping.cart.vo.Cart;
import com.mm.learn.shopping.cart.vo.CartItem;
import com.mm.learn.shopping.cart.vo.UserInfoTo;
import com.mm.learn.interceptor.CartInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wdx
 * @date 2021年07月27日 13:21
 */
@Service
public class CartServiceImpl implements CartService {

    public static Map<Long, CartItem> cartItems = new HashMap<>();

    static {
        CartItem cartItem = new CartItem();
        cartItem.setId(1L);
        cartItem.setPrice(new BigDecimal(20));
        cartItem.setImage("https://gitee.com/wdx13666/images/raw/master/img/20210727213749.png");
        cartItem.setTitle("小米8");
        CartItem cartItem1 = new CartItem();
        cartItem1.setId(2L);
        cartItem1.setPrice(new BigDecimal(30));
        cartItem1.setImage("https://gitee.com/wdx13666/images/raw/master/img/20210710204455.png");
        cartItem1.setTitle("小米9");
        CartItem cartItem2 = new CartItem();
        cartItem2.setId(3L);
        cartItem2.setPrice(new BigDecimal(300));
        cartItem2.setImage("https://gitee.com/wdx13666/images/raw/master/img/20210704204223.png");
        cartItem2.setTitle("小米10");
        cartItems.put(1L, cartItem);
        cartItems.put(2L, cartItem1);
        cartItems.put(3L, cartItem2);
    }


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    private final String CART_PREFIX = "cart:";

    @Override
    public Cart getCart() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
            //登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //如果临时购物车的数据还没有进行合并（合并购物车）
            List<CartItem> temp = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (temp != null) {
                //临时购物车有数据，需要合并
                for (CartItem cartItem : temp) {
                    addToCart(cartItem.getId(), cartItem.getCount());
                }
            }
            //获取登录后的购物车数据【临时和登录后的购物车数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

            //清除临时购物车
            clearCart(CART_PREFIX + userInfoTo.getUserKey());
        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车所有购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSONUtil.toJsonStr(cartItem));
    }

    @Override
    public List<CartItem> getUserCartItemCheck() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            //获取选中的购物项
            if (!CollectionUtils.isEmpty(cartItems)) {
                List<CartItem> collect = cartItems.stream().filter(w -> w.getCheck()).map(w -> {
                    //查询购物项的最新价格 更新为最新价格
                    //w.setPrice();
                    return w;
                }).collect(Collectors.toList());
                return collect;
            }

        }
        return null;
    }

    /**
     * 获取购物车所有购物项
     *
     * @param cartKey
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!values.isEmpty()) {
            List<CartItem> collect = values.stream().map(w -> {
                String s = (String) w;
                CartItem cartItem = JSONUtil.toBean(s, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        return JSONUtil.toBean(s, CartItem.class);
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //购物车无此商品
            //远程查询当前要添加的商品信息 省略 模拟数据
            CartItem cartItem1 = cartItems.get(skuId);
            //商品添加到购物车
            CartItem cartItem = new CartItem();
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setImage(cartItem1.getImage());
            cartItem.setTitle(cartItem1.getTitle());
            cartItem.setId(skuId);
            cartItem.setPrice(cartItem1.getPrice());

            //远程查询sku的组合信息 此处省略

            cartItem.setSkuAttr(Arrays.asList("星河银", "64G"));
            cartOps.put(skuId.toString(), JSONUtil.toJsonStr(cartItem));
            return cartItem;
        } else {
            CartItem cartItem = JSONUtil.toBean(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String s = JSONUtil.toJsonStr(cartItem);
            cartOps.put(skuId.toString(), s);
            return cartItem;
        }

    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = null;
        //登录
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> stringObjectObjectBoundHashOperations =
                stringRedisTemplate.boundHashOps(cartKey);
        return stringObjectObjectBoundHashOperations;
    }
}
